{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 深入 numpy 数组计算\n",
    "# ndarray 更内部的细节，和更高级的数组操作和算法\n",
    "\n",
    "# A.1 ndarray 对象的内部机理\n",
    "# NumPy 的 ndarray 提供了一种将同质数据块（可以是连续或跨越） 解释为多维数组对象的方式\n",
    "#     数据类型（dtype） 决定了数据的解释方式， 比如浮点数、 整数、 布尔值等\n",
    "# ndarray 如此强大的部分原因是所有数组对象都是数据块的一个跨度视图（strided view）\n",
    "\n",
    "# 想知道数组视图 arr[::2,::-1] 不复制任何数据的原因是什么\n",
    "#  简单地说， ndarray 不只是一块内存和一个 dtype，它还有跨度信息，这使得数组能以各种步幅（step size）在内存中移动\n",
    "# 更准确地讲， ndarray 内部由以下内容组成：\n",
    "#     1、一个指向数据（内存或内存映射文件中的一块数据）的指针\n",
    "#     2、数据类型或 dtype， 描述在数组中的固定大小值的格子\n",
    "#     3、一个表示数组形状（shape） 的元组\n",
    "#     4、一个跨度元组（stride），其中的整数指的是为了前进到当前维度下一个元素需要 “跨过” 的字节数\n",
    "\n",
    "# 图 A-1 简单地说明了 ndarray 的内部结构"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![self](./../image/ndarray.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(10, 5)"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 例如， 一个 10×5 的数组， 其形状为(10,5)\n",
    "import numpy as np\n",
    "\n",
    "np.ones((10, 5)).shape\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(160, 40, 8)"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 一个典型的（ C顺序 ） 3×4×5 的 float64（8个字节）数组， 其跨度为 (160,40,8)\n",
    "#    知道跨度是非常有用的， 通常， 跨度在一个轴上越大，沿这个轴进行计算的开销就越大\n",
    "np.ones((3, 4, 5), dtype=np.float64).strides\n",
    "\n",
    "# 虽然 NumPy 用户很少会对数组的跨度信息感兴趣， 但它们却是构建非复制式数组视图的重要因素\n",
    "#   跨度甚至可以是负数， 这样会使数组在内存中后向移动， 比如在切片 obj[::-1] 或 obj[:,::-1] 中就是这样的"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# NumPy 数据类型体系\n",
    "\n",
    "# 可能偶尔需要检查数组中所包含的是否是整数、浮点数、字符串或 Python对象\n",
    "#   因为浮点数的种类很多（从 float16 到 float128 ），判断 dtype 是否属于某个大类的工作非常繁琐\n",
    "# 幸运的是， dtype 都有一个超类（比如 np.integer 和 np.floating），它们可以跟 np.issubdtype 函数结合使用\n",
    "ints = np.ones(10, dtype=np.uint16)\n",
    "\n",
    "floats = np.ones(10, dtype=np.float32)\n",
    "\n",
    "np.issubdtype(ints.dtype, np.integer)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.issubdtype(floats.dtype, np.floating)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[numpy.float64,\n",
       " numpy.floating,\n",
       " numpy.inexact,\n",
       " numpy.number,\n",
       " numpy.generic,\n",
       " float,\n",
       " object]"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 调用 dtype 的 mro 方法即可查看其所有的父类\n",
    "np.float64.mro()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 然后得到：\n",
    "np.issubdtype(ints.dtype, np.number)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 大部分 NumPy 用户完全不需要了解这些知识， 但是这些知识偶尔还是能派上用场的\n",
    "#  图 A-2 说明了 dtype 体系以及父子类关系"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![self](./../image/dtype.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 1, 2, 3, 4, 5, 6, 7])"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# A.2 高级数组操作\n",
    "# 除花式索引、 切片、 布尔条件取子集等操作之外，数组的操作方式还有很多\n",
    "#  虽然 pandas 中的高级函数可以处理数据分析工作中的许多重型任务，但有时还是需要编写一些在现有库中找不到的数据算法\n",
    "\n",
    "\n",
    "# 数组重塑\n",
    "# 多数情况下，可以无需复制任何数据，就将数组从一个形状转换为另一个形状\n",
    "#  只需向数组的实例方法 reshape 传入一个表示新形状的元组即可实现该目的\n",
    "\n",
    "#  例如， 假设有一个一维数组，希望将其重新排列为一个矩阵（结果见图A-3）\n",
    "arr = np.arange(8)\n",
    "\n",
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0, 1],\n",
       "       [2, 3],\n",
       "       [4, 5],\n",
       "       [6, 7]])"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr.reshape((4, 2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![self](./../image/reshape.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0, 1, 2, 3],\n",
       "       [4, 5, 6, 7]])"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 多维数组也能被重塑\n",
    "arr.reshape((4, 2)).reshape((2, 4))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0,  1,  2],\n",
       "       [ 3,  4,  5],\n",
       "       [ 6,  7,  8],\n",
       "       [ 9, 10, 11],\n",
       "       [12, 13, 14]])"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 作为参数的形状的其中一维可以使 -1，它表示该维度的大小有数据本身推断而来\n",
    "arr = np.arange(15)\n",
    "\n",
    "arr.reshape(5, -1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0,  1,  2],\n",
       "       [ 3,  4,  5],\n",
       "       [ 6,  7,  8],\n",
       "       [ 9, 10, 11],\n",
       "       [12, 13, 14]])"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 与 reshape 将一维数组转换为多维数组的运算过程相反的运算通常称之为扁平化（ flattening ）或者散开（ raveling ）\n",
    "arr = np.arange(15).reshape((5, 3))\n",
    "\n",
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14])"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr.ravel()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14])"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 如果结果中的值与原始数组相同， ravel 不会产生源数据的副本\n",
    "# flatten 方法的行为类似于 ravel，只不过它总是返回数据的副本\n",
    "arr.flatten()\n",
    "\n",
    "# 数组可以被重塑或散开为别的顺序\n",
    "#  这对 NumPy 新手来说是一个比较微妙的问题"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0,  1,  2,  3],\n",
       "       [ 4,  5,  6,  7],\n",
       "       [ 8,  9, 10, 11]])"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# C 和 Fortran 顺序\n",
    "# NumPy 允许更为灵活地控制数据在内存中的布局\n",
    "#  默认情况下， NumPy 数组是按 行优先顺序创建的\n",
    "# 在空间方面， 这就意味着， 对于一个二维数组， 每行中的数据项是被存放在相邻内存位置上的\n",
    "# 另一种顺序是 列优先顺序， 它意味着每列中的数据项是被存放在相邻内存位置上的\n",
    "\n",
    "# 由于一些历史原因， 行 和 列优先顺序又分别称为 C 和 Fortran 顺序。 在 FORTRAN 77 中，矩阵全都是列优先的\n",
    "\n",
    "# 像 reshape 和 reval 这样的函数， 都可以接受一个表示数组数据存放顺序的 order 参数\n",
    "#  一般可以 是 'C' 或 'F' （还有 'A' 和 'K' 等不常用的选项，具体请参考 NumPy 的文档）\n",
    "\n",
    "arr = np.arange(12).reshape((3, 4))\n",
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr.ravel()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0,  4,  8,  1,  5,  9,  2,  6, 10,  3,  7, 11])"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr.ravel('F')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 二维 或 高维数组 的重塑过程比较令人费解\n",
    "# C 和 Fortran 顺序的关键区别就是维度的行进顺序：\n",
    "#    - C / 行优先顺序： 先经过更高的维度（例如， 轴 1 会先于 轴 0 被处理）\n",
    "#    - Fortran / 列优先顺序： 后经过更高的维度（例如， 轴 0 会先于 轴 1 被处理）\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 1,  2,  3],\n",
       "       [ 4,  5,  6],\n",
       "       [ 7,  8,  9],\n",
       "       [10, 11, 12]])"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 数组的合并和拆分\n",
    "\n",
    "# numpy.concatenate 可以按指定轴将一个由数组组成的序列（如元组、 列表等）连接到一起：\n",
    "arr1 = np.array([[1, 2, 3], [4, 5, 6]])\n",
    "\n",
    "arr2 = np.array([[7, 8, 9], [10, 11, 12]])\n",
    "\n",
    "np.concatenate([arr1, arr2], axis=0)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 1,  2,  3,  7,  8,  9],\n",
       "       [ 4,  5,  6, 10, 11, 12]])"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.concatenate([arr1, arr2], axis=1)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 1,  2,  3],\n",
       "       [ 4,  5,  6],\n",
       "       [ 7,  8,  9],\n",
       "       [10, 11, 12]])"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 对于常见的连接操作， NumPy 提供了一些比较方便的方法（如 vstack 和 hstack ）\n",
    "#    因此，上面的运算还可以表达为：\n",
    "np.vstack((arr1, arr2))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 1,  2,  3,  7,  8,  9],\n",
       "       [ 4,  5,  6, 10, 11, 12]])"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.hstack((arr1, arr2))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-0.88544376, -0.33460545],\n",
       "       [ 1.2231037 ,  0.28826221],\n",
       "       [-0.23168918, -0.84287813],\n",
       "       [ 0.70697535, -0.18016481],\n",
       "       [-0.14738345, -1.43814099]])"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 与此相反， split 用于将一个数组沿指定轴拆分为多个数组：\n",
    "arr = np.random.randn(5, 2)\n",
    "arr\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-0.88544376, -0.33460545]])"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "first, second, third = np.split(arr, [1, 3])\n",
    "first\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 1.2231037 ,  0.28826221],\n",
       "       [-0.23168918, -0.84287813]])"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "second\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.70697535, -0.18016481],\n",
       "       [-0.14738345, -1.43814099]])"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "third\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 传入到 np.split 的值 [1,3] 指示在哪个索引处分割数组\n",
    "\n",
    "# 表 A-1 中列出了所有关于数组连接和拆分的函数，其中有些是专门为了方便常见的连接运算而提供的"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![self](./../image/numpyfunc.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.        ,  1.        ],\n",
       "       [ 2.        ,  3.        ],\n",
       "       [ 4.        ,  5.        ],\n",
       "       [ 0.79043081, -2.44164348],\n",
       "       [-1.71574535, -0.66465365],\n",
       "       [ 0.94517911,  0.59668795]])"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 堆叠辅助类： r和c\n",
    "# NumPy 命名空间中有两个特殊的对象 —— r 和 c，它们可以使数组的堆叠操作更为简洁\n",
    "arr = np.arange(6)\n",
    "\n",
    "arr1 = arr.reshape((3, 2))\n",
    "\n",
    "arr2 = np.random.randn(3, 2)\n",
    "\n",
    "np.r_[arr1, arr2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.        ,  1.        ,  0.        ],\n",
       "       [ 2.        ,  3.        ,  1.        ],\n",
       "       [ 4.        ,  5.        ,  2.        ],\n",
       "       [ 0.79043081, -2.44164348,  3.        ],\n",
       "       [-1.71574535, -0.66465365,  4.        ],\n",
       "       [ 0.94517911,  0.59668795,  5.        ]])"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.c_[np.r_[arr1, arr2], arr]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[  1, -10],\n",
       "       [  2,  -9],\n",
       "       [  3,  -8],\n",
       "       [  4,  -7],\n",
       "       [  5,  -6]])"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 它还可以将切片转换成数组\n",
    "np.c_[1:6, -10:-5]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [],
   "source": [
    "# r and c , the functions should show the domdcations\n",
    "# r 和 c 的具体功能请参考文档说明"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 1, 2])"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 元素的重复操作： tile 和 repeat\n",
    "# 对数组进行重复以产生更大数组的工具主要是 repeat 和 tile 这两个函数\n",
    "# repeat 会将数组中的各个元素重复一定次数， 从而产生一个更大的数组：\n",
    "arr = np.arange(3)\n",
    "arr\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 0, 0, 1, 1, 1, 2, 2, 2])"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr.repeat(3)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 0, 1, 1, 1, 2, 2, 2, 2])"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 笔记： 跟其他流行的数组编程语言（如 MATLAB ） 不同，NumPy 中很少需要对数组进行重复 replicate\n",
    "#      这主要是因为广播 broadcasting 能更好地满足该需求\n",
    "\n",
    "# 默认情况下， 如果传入的是一个整数， 则各元素就都会重复那么多次\n",
    "#         如果传入的是一组整数，则各元素就可以重复不同的次数\n",
    "arr.repeat([2, 3, 4])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 1.79933192, -0.36278135],\n",
       "       [ 0.12239664, -2.63691588]])"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 对于多维数组， 还可以让它们的元素沿指定轴重复\n",
    "arr = np.random.randn(2, 2)\n",
    "\n",
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 1.79933192, -0.36278135],\n",
       "       [ 1.79933192, -0.36278135],\n",
       "       [ 0.12239664, -2.63691588],\n",
       "       [ 0.12239664, -2.63691588]])"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr.repeat(2, axis=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 1.79933192, -0.36278135],\n",
       "       [ 1.79933192, -0.36278135],\n",
       "       [ 0.12239664, -2.63691588],\n",
       "       [ 0.12239664, -2.63691588],\n",
       "       [ 0.12239664, -2.63691588]])"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 注意， 如果没有设置轴向， 则数组会被扁平化， 这可能不会是你想要的结果\n",
    "#  同样， 在对多维进行重复时， 也可以传入一组整数， 这样就会使各切片重复不同的次数：\n",
    "arr.repeat([2, 3], axis=0)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 1.79933192,  1.79933192, -0.36278135, -0.36278135, -0.36278135],\n",
       "       [ 0.12239664,  0.12239664, -2.63691588, -2.63691588, -2.63691588]])"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr.repeat([2, 3], axis=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 1.79933192, -0.36278135],\n",
       "       [ 0.12239664, -2.63691588]])"
      ]
     },
     "execution_count": 40,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# tile 的功能是沿指定轴向堆叠数组的副本\n",
    "#  可以形象地将其想象成 “ 铺瓷砖 ”\n",
    "arr\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 1.79933192, -0.36278135,  1.79933192, -0.36278135],\n",
       "       [ 0.12239664, -2.63691588,  0.12239664, -2.63691588]])"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.tile(arr, 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 1.79933192, -0.36278135],\n",
       "       [ 0.12239664, -2.63691588]])"
      ]
     },
     "execution_count": 42,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 第二个参数是瓷砖的数量\n",
    "#    对于标量， 瓷砖是水平铺设的， 而不是垂直铺设\n",
    "#    它可以是一个表示 “铺设” 布局的元组\n",
    "arr\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 1.79933192, -0.36278135],\n",
       "       [ 0.12239664, -2.63691588],\n",
       "       [ 1.79933192, -0.36278135],\n",
       "       [ 0.12239664, -2.63691588]])"
      ]
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.tile(arr, (2, 1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 1.79933192, -0.36278135,  1.79933192, -0.36278135],\n",
       "       [ 0.12239664, -2.63691588,  0.12239664, -2.63691588],\n",
       "       [ 1.79933192, -0.36278135,  1.79933192, -0.36278135],\n",
       "       [ 0.12239664, -2.63691588,  0.12239664, -2.63691588],\n",
       "       [ 1.79933192, -0.36278135,  1.79933192, -0.36278135],\n",
       "       [ 0.12239664, -2.63691588,  0.12239664, -2.63691588]])"
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.tile(arr, (3, 2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([700, 100, 200, 600])"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 花式索引的等价函数： take 和 put\n",
    "#     获取和设置数组子集的一个办法是通过整数数组使用花式索引\n",
    "arr = np.arange(10) * 100\n",
    "\n",
    "inds = [7, 1, 2, 6]\n",
    "\n",
    "arr[inds]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([700, 100, 200, 600])"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# ndarray还有其它方法用于获取单个轴向上的选区：\n",
    "arr.take(inds)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([  0,  42,  42, 300, 400, 500,  42,  42, 800, 900])"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr.put(inds, 42)\n",
    "\n",
    "arr\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([  0,  41,  42, 300, 400, 500,  43,  40, 800, 900])"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr.put(inds, [40, 41, 42, 43])\n",
    "arr\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-0.3187673 , -0.31551543,  0.51777074, -0.55135381],\n",
       "       [-0.31756113, -0.46301038,  0.94203497,  2.20608253]])"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 要在其它轴上使用 take， 只需传入 axis 关键字即可：\n",
    "inds = [2, 0, 2, 1]\n",
    "\n",
    "arr = np.random.randn(2, 4)\n",
    "\n",
    "arr\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.51777074, -0.3187673 ,  0.51777074, -0.31551543],\n",
       "       [ 0.94203497, -0.31756113,  0.94203497, -0.46301038]])"
      ]
     },
     "execution_count": 50,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr.take(inds, axis=1)\n",
    "\n",
    "# put 不接受 axis 参数， 它只会在数组的扁平化版本（一维， C顺序） 上进行索引\n",
    "# 因此， 在需要用其他轴向的索引设置元素时， 最好还是使用花式索引"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 1, 2, 3, 4])"
      ]
     },
     "execution_count": 51,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# A.3 广播\n",
    "# 广播 broadcasting 指的是不同形状的数组之间的算术运算的执行方式\n",
    "#  它是一种非常强大的功能， 但也容易令人误解，即使是经验丰富的老手也是如此\n",
    "# 将标量值跟数组合并时就会发生最简单的广播\n",
    "arr = np.arange(5)\n",
    "arr\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0,  4,  8, 12, 16])"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr * 4\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0.24440088,  0.3053056 , -0.43917953])"
      ]
     },
     "execution_count": 53,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 这里说： 在这个乘法运算中， 标量值 4 被广播到了其他所有的元素上\n",
    "\n",
    "# 看一个例子，可以通过减去列平均值的方式对数组的每一列进行距平化处理\n",
    "arr = np.random.randn(4, 3)\n",
    "\n",
    "arr.mean(0)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.01931487,  0.26038097,  1.12778531],\n",
       "       [-0.12161372, -1.21472446, -1.45506915],\n",
       "       [-0.07533828, -0.3011213 , -0.48448045],\n",
       "       [ 0.17763714,  1.25546478,  0.81176429]])"
      ]
     },
     "execution_count": 54,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "demeaned = arr - arr.mean(0)\n",
    "demeaned\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([1.38777878e-17, 0.00000000e+00, 0.00000000e+00])"
      ]
     },
     "execution_count": 55,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "demeaned.mean(0)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 图 A-4 形象地展示了该过程\n",
    "# 用广播的方式对行进行距平化处理会稍微麻烦一些\n",
    "# 幸运的是， 只要遵循一定的规则， 低维度的值是可以被广播到数组的任意维度的（比如对二维数组各列减去行平均值） "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![self](./../image/bordcast.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.26371575,  0.56568658,  0.68860578],\n",
       "       [ 0.12278715, -0.90941886, -1.89424868],\n",
       "       [ 0.16906259,  0.00418431, -0.92365998],\n",
       "       [ 0.42203801,  1.56077038,  0.37258476]])"
      ]
     },
     "execution_count": 57,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 一名经验丰富的 NumPy 老手， 但经常还是得停下来画张图并想想广播的原则\n",
    "\n",
    "# 再来看一下最后那个例子， 假设希望对各行减去那个平均值\n",
    "# 由于 arr.mean(0) 的长度为 3， 所以它可以在  0轴 向上进行广播\n",
    "#   因为 arr 的后缘维度是 3， 所以它们是兼容的\n",
    "# 根据该原则， 要在 1 轴向上做减法（即各行减去行平均值），较小的那个数组的形状必须是 (4,1)\n",
    "\n",
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [],
   "source": [
    "row_means = arr.mean(1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(4,)"
      ]
     },
     "execution_count": 59,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "row_means.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.5060027 ],\n",
       "       [-0.8936268 ],\n",
       "       [-0.25013769],\n",
       "       [ 0.78513105]])"
      ]
     },
     "execution_count": 60,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "row_means.reshape((4, 1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 1.85037171e-17,  1.48029737e-16, -3.70074342e-17, -3.70074342e-17])"
      ]
     },
     "execution_count": 61,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "demeaned = arr - row_means.reshape((4, 1))\n",
    "\n",
    "demeaned.mean(1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 下图说明了该运算的过程"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![self](./../image/mean.png)\n",
    "![self](./../image/gmean.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "operands could not be broadcast together with shapes (4,3) (4,) ",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-63-780e106be00a>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      3\u001b[0m \u001b[1;31m# 高维度数组的广播似乎更难以理解， 而实际上它也是遵循广播原则的\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      4\u001b[0m \u001b[1;31m#  如果不然， 就会得到下面这样一个错误：\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 5\u001b[1;33m \u001b[0marr\u001b[0m \u001b[1;33m-\u001b[0m \u001b[0marr\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mmean\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m: operands could not be broadcast together with shapes (4,3) (4,) "
     ]
    }
   ],
   "source": [
    "# 沿其它轴向广播\n",
    "\n",
    "# 高维度数组的广播似乎更难以理解， 而实际上它也是遵循广播原则的\n",
    "#  如果不然， 就会得到下面这样一个错误：\n",
    "arr - arr.mean(1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-0.24228695,  0.05968387,  0.18260308],\n",
       "       [ 1.01641395, -0.01579206, -1.00062189],\n",
       "       [ 0.41920029,  0.254322  , -0.67352229],\n",
       "       [-0.36309304,  0.77563933, -0.41254629]])"
      ]
     },
     "execution_count": 64,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 人们经常需要通过算术运算过程将较低维度的数组在除 0轴 以外的其他轴向上广播\n",
    "#  根据广播的原则， 较小数组的 “广播维” 必须为 1\n",
    "\n",
    "# 在上面那个行距平化的例子中， 这就意味着要将行平均值的形状变成 (4,1) 而不是 (4,)：\n",
    "arr - arr.mean(1).reshape((4, 1))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 对于三维的情况， 在三维中的任何一维上广播其实也就是将数据重塑为兼容的形状而已\n",
    "#  图 A-7 说明了要在三维数组各维度上广播的形状需求"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![self](./../image/sanarray.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(4, 1, 4)"
      ]
     },
     "execution_count": 66,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 于是就有了一个非常普遍的问题（尤其是在通用算法中），即专门为了广播而添加一个长度为 1 的新轴\n",
    "\n",
    "# 虽然 reshape 是一个办法， 但插入轴需要构造一个表示新形状的元组\n",
    "\n",
    "# 这是一个很郁闷的过程\n",
    "\n",
    "# 因此， NumPy 数组提供了一种通过索引机制插入轴的特殊语法\n",
    "\n",
    "# 下面这段代码通过特殊的 np.newaxis 属性以及 “全”切片 来插入新轴\n",
    "arr = np.zeros((4, 4))\n",
    "\n",
    "arr_3d = arr[:, np.newaxis, :]\n",
    "\n",
    "arr_3d.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-0.37963801],\n",
       "       [ 0.39152934],\n",
       "       [ 0.61525171]])"
      ]
     },
     "execution_count": 67,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr_1d = np.random.normal(size=3)\n",
    "\n",
    "arr_1d[:, np.newaxis]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-0.37963801,  0.39152934,  0.61525171]])"
      ]
     },
     "execution_count": 68,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr_1d[np.newaxis, :]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.02920278,  0.21514078, -0.35293048,  0.4466854 ],\n",
       "       [-0.00240424, -0.00263345, -0.75901032,  0.00582595],\n",
       "       [-0.80417967,  0.2336828 ,  0.13077997, -0.00308872]])"
      ]
     },
     "execution_count": 69,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 因此，如果有一个三维数组，并希望对 轴 2 进行距平化\n",
    "arr = np.random.randn(3, 4, 5)\n",
    "\n",
    "depth_means = arr.mean(2)\n",
    "\n",
    "depth_means"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(3, 4)"
      ]
     },
     "execution_count": 70,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "depth_means.shape\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-1.11022302e-17,  0.00000000e+00,  0.00000000e+00,\n",
       "        -2.22044605e-17],\n",
       "       [ 4.44089210e-17, -4.44089210e-17, -4.44089210e-17,\n",
       "        -8.88178420e-17],\n",
       "       [-4.44089210e-17,  2.22044605e-17,  4.44089210e-17,\n",
       "         2.77555756e-18]])"
      ]
     },
     "execution_count": 71,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "demeaned = arr - depth_means[:, :, np.newaxis]\n",
    "\n",
    "demeaned.mean(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 可能会想， 在对指定轴进行距平化时， 有没有一种既通用又不牺牲性能的方法呢？ \n",
    "# 实际上是有的， 但需要一些索引方面的技巧\n",
    "\n",
    "def demean_axis(arr, axis=0):\n",
    "    means = arr.mean(axis)\n",
    "    # This generalizes things like [:, :, np.newaxis] to N dimensions\n",
    "    indexer = [slice(None)] * arr.ndim\n",
    "    indexer[axis] = np.newaxis\n",
    "    return arr - means[indexer]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[5., 5., 5.],\n",
       "       [5., 5., 5.],\n",
       "       [5., 5., 5.],\n",
       "       [5., 5., 5.]])"
      ]
     },
     "execution_count": 73,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 通过广播设置数组的值\n",
    "# 算术运算所遵循的广播原则同样也适用于通过索引机制设置数组值的操作\n",
    "\n",
    "#  对于最简单的情况，这样做\n",
    "arr = np.zeros((4, 3))\n",
    "\n",
    "arr[:] = 5\n",
    "\n",
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 1.28,  1.28,  1.28],\n",
       "       [-0.42, -0.42, -0.42],\n",
       "       [ 0.44,  0.44,  0.44],\n",
       "       [ 1.6 ,  1.6 ,  1.6 ]])"
      ]
     },
     "execution_count": 74,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 但是， 假设想要用一个一维数组来设置目标数组的各列， 只要保证形状兼容就可以了：\n",
    "col = np.array([1.28, -0.42, 0.44, 1.6])\n",
    "\n",
    "arr[:] = col[:, np.newaxis]\n",
    "\n",
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-1.37 , -1.37 , -1.37 ],\n",
       "       [ 0.509,  0.509,  0.509],\n",
       "       [ 0.44 ,  0.44 ,  0.44 ],\n",
       "       [ 1.6  ,  1.6  ,  1.6  ]])"
      ]
     },
     "execution_count": 75,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr[:2] = [[-1.37], [0.509]]\n",
    "\n",
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "45"
      ]
     },
     "execution_count": 76,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# A.4 ufunc高级应用\n",
    "# 虽然许多 NumPy 用户只会用到通用函数所提供的快速的元素级运算， \n",
    "# 但通用函数实际上还有一些高级用法能使丢开循环而编写出更为简洁的代码\n",
    "\n",
    "# ufunc 实例方法\n",
    "# NumPy 的各个二元 ufunc 都有一些用于执行特定矢量化运算的特殊方法\n",
    "\n",
    "# reduce 接受一个数组参数，并通过一系列的二元运算对其值进行聚合（可指明轴向）\n",
    "#  例如，可以用 np.add.reduce 对数组中各个元素进行求和\n",
    "arr = np.arange(10)\n",
    "\n",
    "np.add.reduce(arr)\n",
    "\n",
    "arr.sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ True,  True,  True,  True],\n",
       "       [False,  True, False, False],\n",
       "       [ True,  True,  True,  True],\n",
       "       [ True, False,  True,  True],\n",
       "       [ True,  True,  True,  True]])"
      ]
     },
     "execution_count": 77,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 起始值取决于 ufunc（对于 add 的情况， 就是 0）\n",
    "#  如果设置了轴号， 约简运算就会沿该轴向执行\n",
    "\n",
    "# 这就使能用一种比较简洁的方式得到某些问题的答案\n",
    "\n",
    "# np.logical_and 检查数组各行中的值是否是有序的：\n",
    "np.random.seed(12346) # for reproducibility\n",
    "\n",
    "arr = np.random.randn(5, 5)\n",
    "\n",
    "arr[::2].sort(1) # sort a few rows\n",
    "\n",
    "arr[:, :-1] < arr[:, 1:]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 78,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ True, False,  True, False,  True])"
      ]
     },
     "execution_count": 78,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.logical_and.reduce(arr[:, :-1] < arr[:, 1:], axis=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0,  1,  3,  6, 10],\n",
       "       [ 5, 11, 18, 26, 35],\n",
       "       [10, 21, 33, 46, 60]], dtype=int32)"
      ]
     },
     "execution_count": 79,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 注意， logical_and.reduce 跟 all 方法是等价的\n",
    "# ccumulate 跟 reduce 的关系就像 cumsum 跟 sum 的关系那样\n",
    "#  它产生一个跟原数组大小相同的中间 “累计” 值数组\n",
    "arr = np.arange(15).reshape((3, 5))\n",
    "\n",
    "np.add.accumulate(arr, axis=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 80,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 1, 1, 2, 2])"
      ]
     },
     "execution_count": 80,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# outer 用于计算两个数组的叉积\n",
    "arr = np.arange(3).repeat([1, 2, 2])\n",
    "\n",
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0, 0, 0, 0, 0],\n",
       "       [0, 1, 2, 3, 4],\n",
       "       [0, 1, 2, 3, 4],\n",
       "       [0, 2, 4, 6, 8],\n",
       "       [0, 2, 4, 6, 8]])"
      ]
     },
     "execution_count": 81,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.multiply.outer(arr, np.arange(5))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(3, 4, 5)"
      ]
     },
     "execution_count": 82,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# outer 输出结果的维度是两个输入数据的维度之和：\n",
    "x, y = np.random.randn(3, 4), np.random.randn(5)\n",
    "\n",
    "result = np.subtract.outer(x, y)\n",
    "\n",
    "result.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([10, 18, 17], dtype=int32)"
      ]
     },
     "execution_count": 83,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 最后一个方法 reduceat 用于计算 “局部约简”， 其实就是一个对数据各切片进行聚合的 groupby 运算\n",
    "#  它接受一组用于指示如何对值进行拆分和聚合的 “面元边界”\n",
    "arr = np.arange(10)\n",
    "\n",
    "np.add.reduceat(arr, [0, 5, 8])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 84,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0,  0,  0,  0,  0],\n",
       "       [ 0,  1,  2,  3,  4],\n",
       "       [ 0,  2,  4,  6,  8],\n",
       "       [ 0,  3,  6,  9, 12]])"
      ]
     },
     "execution_count": 84,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 最终结果是在 arr[0:5]、 arr[5:8] 以及 arr[8:] 上执行的约简\n",
    "\n",
    "# 跟其他方法一样， 这里也可以传入一个 axis 参数：\n",
    "arr = np.multiply.outer(np.arange(4), np.arange(5))\n",
    "\n",
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0,  0,  0],\n",
       "       [ 1,  5,  4],\n",
       "       [ 2, 10,  8],\n",
       "       [ 3, 15, 12]], dtype=int32)"
      ]
     },
     "execution_count": 85,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.add.reduceat(arr, [0, 2, 4], axis=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![self](./../image/ufunc.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 86,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 2, 4, 6, 8, 10, 12, 14], dtype=object)"
      ]
     },
     "execution_count": 86,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 编写新的ufunc\n",
    "\n",
    "# 有多种方法可以编写自己的 NumPy ufuncs\n",
    "# 最常见的是使用 NumPy C API，但它超越了本书的范围\n",
    "\n",
    "# 讲纯粹的 Python ufunc\n",
    "# numpy.frompyfunc 接受一个 Python 函数以及两个分别表示输入输出参数数量的参数\n",
    "\n",
    "# 例如，下面是一个能够实现元素级加法的简单函数\n",
    "def add_elements(x, y):\n",
    "    return x + y\n",
    "\n",
    "add_them = np.frompyfunc(add_elements, 2, 1)\n",
    "\n",
    "add_them(np.arange(8), np.arange(8))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0.,  2.,  4.,  6.,  8., 10., 12., 14.])"
      ]
     },
     "execution_count": 87,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 用 frompyfunc 创建的函数总是返回 Python 对象数组， 这一点很不方便\n",
    "\n",
    "#  幸运的是， 还有另一个办法， 即 numpy.vectorize\n",
    "\n",
    "# 虽然没有 frompyfunc 那么强大， 但可以指定输出类型\n",
    "add_them = np.vectorize(add_elements, otypes=[np.float64])\n",
    "\n",
    "add_them(np.arange(8), np.arange(8))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 88,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4.62 ms ± 86.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
     ]
    }
   ],
   "source": [
    "# 虽然这两个函数提供了一种创建 ufunc 型函数的手段， 但它们非常慢， \n",
    "#    因为它们在计算每个元素时都要执行一次 Python 函数调用， 这就会比 NumPy 自带的基于 C 的 ufunc 慢很多\n",
    "arr = np.random.randn(10000)\n",
    "\n",
    "%timeit add_them(arr, arr)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "14.6 µs ± 192 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n"
     ]
    }
   ],
   "source": [
    "%timeit np.add(arr, arr)\n",
    "\n",
    "# 介绍使用 Numba（http://numba.pydata.org/），创建快速 Python ufuncs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 91,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([(1.5       ,  6), (3.14159265, -2)],\n",
       "      dtype=[('x', '<f8'), ('y', '<i4')])"
      ]
     },
     "execution_count": 91,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# A.5 结构化和记录式数组\n",
    "\n",
    "# 可能已经注意到了， 到目前为止所讨论的 ndarray 都是一种同质数据容器，\n",
    "#  也就是说， 在它所表示的内存块中， 各元素占用的字节数相同（具体根据 dtype 而定）\n",
    "\n",
    "# 从表面上看， 它似乎不能用于表示异质或表格型的数据\n",
    "\n",
    "# 结构化数组是一种特殊的 ndarray， 其中的各个元素可以被看做 C 中的结构体 struct 或 SQL 表中带有多个命名字段的行\n",
    "dtype = [('x', np.float64), ('y', np.int32)]\n",
    "\n",
    "sarr = np.array([(1.5, 6), (np.pi, -2)], dtype=dtype)\n",
    "\n",
    "sarr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 92,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(1.5, 6)"
      ]
     },
     "execution_count": 92,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 定义结构化 dtype（请参考 NumPy 的在线文档） 的方式有很多\n",
    "\n",
    "# 最典型的办法是元组列表， 各元组的格式为 (field_name,field_data_type)\n",
    "# 这样， 数组的元素就成了元组式的对象， 该对象中各个元素可以像字典那样进行访问：\n",
    "sarr[0]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 93,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6"
      ]
     },
     "execution_count": 93,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sarr[0]['y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 94,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([1.5       , 3.14159265])"
      ]
     },
     "execution_count": 94,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 字段名保存在 dtype.names 属性中\n",
    "#  在访问结构化数组的某个字段时， 返回的是该数据的视图， 所以不会发生数据复制：\n",
    "sarr['x']\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 95,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([([0, 0, 0], 0), ([0, 0, 0], 0), ([0, 0, 0], 0), ([0, 0, 0], 0)],\n",
       "      dtype=[('x', '<i8', (3,)), ('y', '<i4')])"
      ]
     },
     "execution_count": 95,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 嵌套 dtype 和 多维字段\n",
    "\n",
    "# 在定义结构化 dtype 时，可以再设置一个形状（可以是一个整数， 也可以是一个元组）\n",
    "dtype = [('x', np.int64, 3), ('y', np.int32)]\n",
    "\n",
    "arr = np.zeros(4, dtype=dtype)\n",
    "\n",
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 96,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 0, 0], dtype=int64)"
      ]
     },
     "execution_count": 96,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 在这种情况下， 各个记录的 x 字段所表示的是一个长度为 3 的数组\n",
    "arr[0]['x']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0, 0, 0],\n",
       "       [0, 0, 0],\n",
       "       [0, 0, 0],\n",
       "       [0, 0, 0]], dtype=int64)"
      ]
     },
     "execution_count": 97,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 这样， 访问 arr['x'] 即可得到一个二维数组，而不是前面那个例子中的一维数组\n",
    "arr['x']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 98,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([(1., 2.), (3., 4.)], dtype=[('a', '<f8'), ('b', '<f4')])"
      ]
     },
     "execution_count": 98,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 这就使能用单个数组的内存块存放复杂的嵌套结构\n",
    "\n",
    "# 还可以嵌套 dtype， 作出更复杂的结构\n",
    "dtype = [('x', [('a', 'f8'), ('b', 'f4')]), ('y', np.int32)]\n",
    "\n",
    "data = np.array([((1, 2), 5), ((3, 4), 6)], dtype=dtype)\n",
    "\n",
    "data['x']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 99,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([5, 6])"
      ]
     },
     "execution_count": 99,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data['y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 100,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([1., 3.])"
      ]
     },
     "execution_count": 100,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data['x']['a']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 101,
   "metadata": {},
   "outputs": [],
   "source": [
    "# pandas 的 DataFrame 并不直接支持该功能， 但它的分层索引机制跟这个差不多\n",
    "\n",
    "\n",
    "# 为什么要用结构化数组\n",
    "# 跟 pandas 的 DataFrame 相比， NumPy 的结构化数组是一种相对较低级的工具\n",
    "#  它可以将单个内存块解释为带有任意复杂嵌套列的表格型结构\n",
    "\n",
    "# 由于数组中的每个元素在内存中都被表示为固定的字节数，\n",
    "#  所以结构化数组能够提供非常快速高效的磁盘数据读写（包括内存映像）、网络传输等功能\n",
    "\n",
    "# 结构化数组的另一个常见用法是， 将数据文件写成定长记录字节流， 这是 C 和 C++ 代码中常见的数据序列化手段（业界许多历史系统中都能找得到）\n",
    "# 只要知道文件的格式（记录的大小、元素的顺序、字节数以及数据类型等），就可以用 np.fromfile 将数据读入内存"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 102,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([-1.08199644,  0.37588273,  0.80139193,  1.13969136,  1.28881614,\n",
       "        1.84126094])"
      ]
     },
     "execution_count": 102,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# A.6 更多有关排序的话题\n",
    "\n",
    "# 跟 Python 内置的列表一样， ndarray 的 sort 实例方法也是就地排序\n",
    "# 也就是说， 数组内容的重新排列是不会产生新数组的\n",
    "arr = np.random.randn(6)\n",
    "\n",
    "arr.sort()\n",
    "\n",
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 103,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-0.33176812, -1.47108206,  0.87050269, -0.08468875, -1.13286962],\n",
       "       [-1.01114869, -0.34357617,  2.17140268,  0.12337075, -0.01893118],\n",
       "       [ 0.17731791,  0.7423957 ,  0.85475634,  1.03797268, -0.32899594]])"
      ]
     },
     "execution_count": 103,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 在对数组进行就地排序时要注意一点， 如果目标数组只是一个视图， 则原始数组将会被修改\n",
    "arr = np.random.randn(3, 5)\n",
    "\n",
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 104,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-1.01114869, -1.47108206,  0.87050269, -0.08468875, -1.13286962],\n",
       "       [-0.33176812, -0.34357617,  2.17140268,  0.12337075, -0.01893118],\n",
       "       [ 0.17731791,  0.7423957 ,  0.85475634,  1.03797268, -0.32899594]])"
      ]
     },
     "execution_count": 104,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr[:, 0].sort() # Sort first column values in-place\n",
    "\n",
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 105,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([-1.11807759, -0.24152521, -2.0051193 ,  0.73788753, -1.06137462])"
      ]
     },
     "execution_count": 105,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 相反， numpy.sort 会为原数组创建一个已排序副本\n",
    "\n",
    "#  另外， 它所接受的参数（比如 kind ） 跟 ndarray.sort 一样\n",
    "arr = np.random.randn(5)\n",
    "\n",
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 106,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([-2.0051193 , -1.11807759, -1.06137462, -0.24152521,  0.73788753])"
      ]
     },
     "execution_count": 106,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.sort(arr)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 107,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([-1.11807759, -0.24152521, -2.0051193 ,  0.73788753, -1.06137462])"
      ]
     },
     "execution_count": 107,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 108,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.59545348, -0.26822958,  1.33885804, -0.18715572,  0.91108374],\n",
       "       [-0.32150045,  1.00543901, -0.51683937,  1.19251887, -0.19893404],\n",
       "       [ 0.39691349, -1.76381537,  0.60709023, -0.22215536, -0.21707838]])"
      ]
     },
     "execution_count": 108,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 这两个排序方法都可以接受一个 axis 参数， 以便沿指定轴向对各块数据进行单独排序：\n",
    "arr = np.random.randn(3, 5)\n",
    "\n",
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 109,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-0.26822958, -0.18715572,  0.59545348,  0.91108374,  1.33885804],\n",
       "       [-0.51683937, -0.32150045, -0.19893404,  1.00543901,  1.19251887],\n",
       "       [-1.76381537, -0.22215536, -0.21707838,  0.39691349,  0.60709023]])"
      ]
     },
     "execution_count": 109,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr.sort(axis=1)\n",
    "\n",
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 110,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 1.33885804,  0.91108374,  0.59545348, -0.18715572, -0.26822958],\n",
       "       [ 1.19251887,  1.00543901, -0.19893404, -0.32150045, -0.51683937],\n",
       "       [ 0.60709023,  0.39691349, -0.21707838, -0.22215536, -1.76381537]])"
      ]
     },
     "execution_count": 110,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 可能注意到了， 这两个排序方法都不可以被设置为降序\n",
    "#  其实这也无所谓， 因为数组切片会产生视图（也就是说， 不会产生副本， 也不需要任何其他的计算工作）\n",
    "\n",
    "# 许多 Python 用户都很熟悉一个有关列表的小技巧：\n",
    "#    values[::-1] 可以返回一个反序的列表\n",
    "\n",
    "#  对 ndarray 也是如此\n",
    "arr[:, ::-1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 111,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([1, 2, 4, 3, 0], dtype=int64)"
      ]
     },
     "execution_count": 111,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 间接排序： argsort和lexsort\n",
    "\n",
    "# 在数据分析工作中， 常常需要根据一个或多个键对数据集进行排序\n",
    "\n",
    "#  例如， 一个有关学生信息的数据表可能需要以姓和名进行排序（先姓后名）\n",
    "#  这就是间接排序的一个例子， 如果阅读过有关 pandas 的章节， 那就已经见过不少高级例子了\n",
    "\n",
    "#  给定一个或多个键， 可以得到一个由整数组成的索引数组（亲切地称之为索引器），\n",
    "#   其中的索引值说明了数据在新顺序下的位置\n",
    "\n",
    "#  argsort 和 numpy.lexsort 就是实现该功能的两个主要方法\n",
    "\n",
    "values = np.array([5, 0, 1, 3, 2])\n",
    "\n",
    "indexer = values.argsort()\n",
    "\n",
    "indexer\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 112,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 1, 2, 3, 5])"
      ]
     },
     "execution_count": 112,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "values[indexer]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 113,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 5.        ,  0.        ,  1.        ,  3.        ,  2.        ],\n",
       "       [-0.36360302, -0.13775933,  2.17773731, -0.47280687,  0.8356152 ],\n",
       "       [-0.20885016,  0.23159352,  0.72798172, -1.3918432 ,  1.99558262]])"
      ]
     },
     "execution_count": 113,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 一个更复杂的例子， 下面这段代码根据数组的第一行对其进行排序：\n",
    "arr = np.random.randn(3, 5)\n",
    "\n",
    "arr[0] = values\n",
    "\n",
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 114,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.        ,  1.        ,  2.        ,  3.        ,  5.        ],\n",
       "       [-0.13775933,  2.17773731,  0.8356152 , -0.47280687, -0.36360302],\n",
       "       [ 0.23159352,  0.72798172,  1.99558262, -1.3918432 , -0.20885016]])"
      ]
     },
     "execution_count": 114,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr[:, arr[0].argsort()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 115,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([1, 2, 3, 0, 4], dtype=int64)"
      ]
     },
     "execution_count": 115,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# lexsort 跟 argsort 差不多，只不过它可以一次性对多个键数组执行间接排序（字典序）\n",
    "\n",
    "# 假设想对一些以姓和名标识的数据进行排序：\n",
    "first_name = np.array(['Bob', 'Jane', 'Steve', 'Bill', 'Barbara'])\n",
    "\n",
    "last_name = np.array(['Jones', 'Arnold', 'Arnold', 'Jones', 'Walters'])\n",
    "\n",
    "sorter = np.lexsort((first_name, last_name))\n",
    "\n",
    "sorter"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 116,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<zip at 0x606df48>"
      ]
     },
     "execution_count": 116,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "zip(last_name[sorter], first_name[sorter])\n",
    "\n",
    "# 刚开始使用 lexsort 的时候可能会比较容易头晕， 这是因为键的应用顺序是从最后一个传入的算起的\n",
    "\n",
    "#  不难看出， last_name 是先于 first_name 被应用的\n",
    "# 笔记： Series 和 DataFrame 的 sort_index 以及 Series 的 order 方法就是通过这些函数的变体(它们还必须考虑缺失值)实现的"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 117,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([2, 3, 4, 0, 1], dtype=int64)"
      ]
     },
     "execution_count": 117,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 其他排序算法\n",
    "\n",
    "# 稳定的（stable） 排序算法会保持等价元素的相对位置\n",
    "#  对于相对位置具有实际意义的那些间接排序而言， 这一点非常重要：\n",
    "values = np.array(['2:first', '2:second', '1:first', '1:second', '1:third'])\n",
    "\n",
    "key = np.array([2, 2, 1, 1, 1])\n",
    "\n",
    "indexer = key.argsort(kind='mergesort')\n",
    "\n",
    "indexer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 118,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array(['1:first', '1:second', '1:third', '2:first', '2:second'],\n",
       "      dtype='<U8')"
      ]
     },
     "execution_count": 118,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "values.take(indexer)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 119,
   "metadata": {},
   "outputs": [],
   "source": [
    "# mergesort（合并排序） 是唯一的稳定排序， 它保证有 O(nlogn) 的性能（空间复杂度），\n",
    "# 但是其平均性能比默认的 quicksort（快速排序）要差\n",
    "\n",
    "# 表 A-3 列出了可用的排序算法及其相关的性能指标\n",
    "# 大部分用户完全不需要知道这些东西， 但了解一下总是好的"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![self](./../image/sort.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 120,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([-0.20470766,  0.47894334, -0.51943872, -0.5557303 ,  1.96578057,\n",
       "        1.39340583,  0.09290788,  0.28174615,  0.76902257,  1.24643474,\n",
       "        1.00718936, -1.29622111,  0.27499163,  0.22891288,  1.35291684,\n",
       "        0.88642934, -2.00163731, -0.37184254,  1.66902531, -0.43856974])"
      ]
     },
     "execution_count": 120,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 部分排序数组\n",
    "\n",
    "# 排序的目的之一可能是确定数组中最大或最小的元素\n",
    "\n",
    "# NumPy 有两个优化方法， numpy.partition 和 np.argpartition，可以在第 k 个最小元素划分的数组\n",
    "np.random.seed(12345)\n",
    "\n",
    "arr = np.random.randn(20)\n",
    "\n",
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 121,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([-2.00163731, -1.29622111, -0.5557303 , -0.51943872, -0.37184254,\n",
       "       -0.43856974, -0.20470766,  0.28174615,  0.76902257,  0.47894334,\n",
       "        1.00718936,  0.09290788,  0.27499163,  0.22891288,  1.35291684,\n",
       "        0.88642934,  1.39340583,  1.96578057,  1.66902531,  1.24643474])"
      ]
     },
     "execution_count": 121,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.partition(arr, 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 122,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([16, 11,  3,  2, 17, 19,  0,  7,  8,  1, 10,  6, 12, 13, 14, 15,  5,\n",
       "        4, 18,  9], dtype=int64)"
      ]
     },
     "execution_count": 122,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 当调用 partition(arr, 3)，结果中的头三个元素是最小的三个，没有特定的顺序\n",
    "\n",
    "# numpy.argpartition 与 numpy.argsort 相似，会返回索引，重排数据为等价的顺序：\n",
    "indices = np.argpartition(arr, 3)\n",
    "\n",
    "indices"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 123,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([-2.00163731, -1.29622111, -0.5557303 , -0.51943872, -0.37184254,\n",
       "       -0.43856974, -0.20470766,  0.28174615,  0.76902257,  0.47894334,\n",
       "        1.00718936,  0.09290788,  0.27499163,  0.22891288,  1.35291684,\n",
       "        0.88642934,  1.39340583,  1.96578057,  1.66902531,  1.24643474])"
      ]
     },
     "execution_count": 123,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr.take(indices)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 124,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 124,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# numpy.searchsorted： 在有序数组中查找元素\n",
    "# searchsorted 是一个在有序数组上执行二分查找的数组方法，\n",
    "# 只要将值插入到它返回的那个位置就能维持数组的有序性：\n",
    "\n",
    "arr = np.array([0, 1, 7, 12, 15])\n",
    "\n",
    "arr.searchsorted(9)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 125,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 3, 3, 5], dtype=int64)"
      ]
     },
     "execution_count": 125,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 可以传入一组值就能得到一组索引：\n",
    "arr.searchsorted([0, 8, 11, 16])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 126,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 3], dtype=int64)"
      ]
     },
     "execution_count": 126,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 从上面的结果中可以看出，对于元素 0，searchsorted 会返回 0\n",
    "# 这是因为其默认行为是返回相等值组的左侧索引：\n",
    "arr = np.array([0, 0, 0, 1, 1, 1, 1])\n",
    "\n",
    "arr.searchsorted([0, 1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 127,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([3, 7], dtype=int64)"
      ]
     },
     "execution_count": 127,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr.searchsorted([0, 1], side='right')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 128,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([9940., 6768., 7908., 1709.,  268., 8003., 9037.,  246., 4917.,\n",
       "       5262., 5963.,  519., 8950., 7282., 8183., 5002., 8101.,  959.,\n",
       "       2189., 2587., 4681., 4593., 7095., 1780., 5314., 1677., 7688.,\n",
       "       9281., 6094., 1501., 4896., 3773., 8486., 9110., 3838., 3154.,\n",
       "       5683., 1878., 1258., 6875., 7996., 5735., 9732., 6340., 8884.,\n",
       "       4954., 3516., 7142., 5039., 2256.])"
      ]
     },
     "execution_count": 128,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 再来看 searchsorted 的另一个用法， \n",
    "# 假设有一个数据数组（其中的值在0到10000之间）\n",
    "# 还有一个表示 “面元边界” 的数组，希望用它将数据数组拆分开：\n",
    "data = np.floor(np.random.uniform(0, 10000, size=50))\n",
    "\n",
    "bins = np.array([0, 100, 1000, 5000, 10000])\n",
    "\n",
    "data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 129,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([4, 4, 4, 3, 2, 4, 4, 2, 3, 4, 4, 2, 4, 4, 4, 4, 4, 2, 3, 3, 3, 3,\n",
       "       4, 3, 4, 3, 4, 4, 4, 3, 3, 3, 4, 4, 3, 3, 4, 3, 3, 4, 4, 4, 4, 4,\n",
       "       4, 3, 3, 4, 4, 3], dtype=int64)"
      ]
     },
     "execution_count": 129,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 然后， 为了得到各数据点所属区间的编号（其中1表示面元[0,100)）\n",
    "# 可以直接使用 searchsorted：\n",
    "labels = bins.searchsorted(data)\n",
    "\n",
    "labels"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 131,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2     498.000000\n",
       "3    3064.277778\n",
       "4    7389.035714\n",
       "dtype: float64"
      ]
     },
     "execution_count": 131,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 通过 pandas 的 groupby 使用该结果即可非常轻松地对原数据集进行拆分\n",
    "import pandas as pd\n",
    "pd.Series(data).groupby(labels).mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 132,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "16.9 s ± 145 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
     ]
    }
   ],
   "source": [
    "# A.7 用Numba编写快速NumPy函数\n",
    "\n",
    "# Numba 是一个开源项目， 它可以利用 CPUs、 GPUs 或其它硬件为类似 NumPy 的数据创建快速函数\n",
    "\n",
    "#它使用了 LLVM 项目（http://llvm.org/），将 Python 代码转换为机器代码\n",
    "\n",
    "# 为了介绍 Numba，来考虑一个纯粹的 Python 函数，它使用 for 循环计算表达式 (x - y).mean()：\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "def mean_distance(x, y):\n",
    "    nx = len(x)\n",
    "    result = 0.0\n",
    "    count = 0\n",
    "    for i in range(nx):\n",
    "        result += x[i] - y[i]\n",
    "        count += 1\n",
    "    return result / count\n",
    "\n",
    "# 这个函数很慢：\n",
    "x = np.random.randn(10000000)\n",
    "\n",
    "y = np.random.randn(10000000)\n",
    "\n",
    "%timeit mean_distance(x, y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 133,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "140 ms ± 3.27 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
     ]
    }
   ],
   "source": [
    "%timeit (x - y).mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 134,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "32.5 ms ± 3.57 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n"
     ]
    }
   ],
   "source": [
    "# NumPy 的版本要比它快过 100 倍\n",
    "\n",
    "# 可以转换这个函数为编译的 Numba 函数， 使用 numba.jit 函数\n",
    "import numba as nb\n",
    "\n",
    "numba_mean_distance = nb.jit(mean_distance)\n",
    "\n",
    "# 也可以写成装饰器：\n",
    "@nb.jit\n",
    "def mean_distance(x, y):\n",
    "    nx = len(x)\n",
    "    result = 0.0\n",
    "    count = 0\n",
    "    for i in range(nx):\n",
    "        result += x[i] - y[i]\n",
    "        count += 1\n",
    "    return result / count\n",
    "\n",
    "\n",
    "# 它要比矢量化的 NumPy 快\n",
    "%timeit numba_mean_distance(x, y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 135,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Numba 不能编译 Python 代码，但它支持纯 Python 写的一个部分， 可以编写数值算法\n",
    "\n",
    "# Numba 是一个深厚的库， 支持多种硬件、 编译模式和用户插件\n",
    "# 它还可以编译 NumPy Python API 的一部分， 而不用 for 循环\n",
    "#  Numba 也可以识别可以便以为机器编码的结构体， 但是若调用 CPython API，它就不知道如何编译\n",
    "\n",
    "#  Numba 的 jit 函数有一个选项， nopython=True， 它限制了可以被转换为 Python 代码的代码，\n",
    "# 这些代码可以编译为 LLVM， 但没有任何 Python C API调用\n",
    "\n",
    "# jit(nopython=True) 有一个简短的别名 numba.njit\n",
    "\n",
    "# 前面的例子， 还可以这样写：\n",
    "from numba import float64, njit\n",
    "\n",
    "@njit(float64(float64[:], float64[:]))\n",
    "def mean_distance(x, y):\n",
    "    return (x - y).mean()\n",
    "\n",
    "\n",
    "# 建议学习 Numba 的线上文档（http://numba.pydata.org/）\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 163,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18], dtype=int64)"
      ]
     },
     "execution_count": 163,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 用 Numba 创建自定义 numpy.ufunc 对象\n",
    "# numba.vectorize 创建了一个编译的 NumPy ufunc， 它与内置的 ufunc 很像\n",
    "\n",
    "# 考虑一个 numpy.add 的 Python 例子\n",
    "from numba import vectorize\n",
    "@vectorize\n",
    "def nb_add(x, y):\n",
    "    return x + y\n",
    "\n",
    "x = np.arange(10)\n",
    "\n",
    "nb_add(x, x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 164,
   "metadata": {},
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "could not find a matching type for nb_add.accumulate, requested type has type code 'l'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-164-e53ce9bd412f>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mnb_add\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0maccumulate\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mx\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m0\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m: could not find a matching type for nb_add.accumulate, requested type has type code 'l'"
     ]
    }
   ],
   "source": [
    "# why why why why why why\n",
    "nb_add.accumulate(x, 0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 145,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "memmap([[0., 0., 0., ..., 0., 0., 0.],\n",
       "        [0., 0., 0., ..., 0., 0., 0.],\n",
       "        [0., 0., 0., ..., 0., 0., 0.],\n",
       "        ...,\n",
       "        [0., 0., 0., ..., 0., 0., 0.],\n",
       "        [0., 0., 0., ..., 0., 0., 0.],\n",
       "        [0., 0., 0., ..., 0., 0., 0.]])"
      ]
     },
     "execution_count": 145,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# A.8 高级数组输入输出\n",
    "\n",
    "# np.save 和 np.load 可用于读写磁盘上以二进制格式存储的数组\n",
    "#  其实还有一些工具可用于更为复杂的场景\n",
    "\n",
    "# 尤其是内存映像（memory map），它能处理在内存中放不下的数据集\n",
    "\n",
    "# 内存映像文件\n",
    "# 内存映像文件是一种将磁盘上的非常大的二进制数据文件当做内存中的数组进行处理的方式\n",
    "\n",
    "# NumPy 实现了一个类似于 ndarray 的 memmap 对象，它允许将大文件分成小段进行读写，而不是一次性将整个数组读入内存\n",
    "# 另外， memmap 也拥有跟普通数组一样的方法， 因此， 基本上只要是能用于 ndarray 的算法就也能用于 memmap\n",
    "\n",
    "# 要创建一个内存映像， 可以使用函数 np.memmap 并传入一个文件路径、 数据类型、 形状以及文件模式：\n",
    "mmap = np.memmap('mymmap', dtype='float64', mode='w+', shape=(10000, 10000))\n",
    "\n",
    "mmap"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 146,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 对 memmap 切片将会返回磁盘上的数据的视图：\n",
    "section = mmap[:5]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 147,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "memmap([[ 1.37140985,  0.93127837,  0.60573747, ..., -0.62115557,\n",
       "         -0.46780136,  0.47874865],\n",
       "        [ 0.42296545,  0.83060431,  0.69976547, ...,  1.28831447,\n",
       "          0.58858679, -1.42755372],\n",
       "        [ 2.16005954, -1.24616489,  2.44470054, ...,  0.86866129,\n",
       "          0.28019716,  2.13008671],\n",
       "        ...,\n",
       "        [ 0.        ,  0.        ,  0.        , ...,  0.        ,\n",
       "          0.        ,  0.        ],\n",
       "        [ 0.        ,  0.        ,  0.        , ...,  0.        ,\n",
       "          0.        ,  0.        ],\n",
       "        [ 0.        ,  0.        ,  0.        , ...,  0.        ,\n",
       "          0.        ,  0.        ]])"
      ]
     },
     "execution_count": 147,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 如果将数据赋值给这些视图： 数据会先被缓存在内存中（就像是 Python 的文件对象），\n",
    "# 调用 flush 即可将其写入磁盘：\n",
    "section[:] = np.random.randn(5, 10000)\n",
    "\n",
    "mmap.flush()\n",
    "\n",
    "mmap"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 148,
   "metadata": {},
   "outputs": [],
   "source": [
    "del mmap"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 149,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "memmap([[ 1.37140985,  0.93127837,  0.60573747, ..., -0.62115557,\n",
       "         -0.46780136,  0.47874865],\n",
       "        [ 0.42296545,  0.83060431,  0.69976547, ...,  1.28831447,\n",
       "          0.58858679, -1.42755372],\n",
       "        [ 2.16005954, -1.24616489,  2.44470054, ...,  0.86866129,\n",
       "          0.28019716,  2.13008671],\n",
       "        ...,\n",
       "        [ 0.        ,  0.        ,  0.        , ...,  0.        ,\n",
       "          0.        ,  0.        ],\n",
       "        [ 0.        ,  0.        ,  0.        , ...,  0.        ,\n",
       "          0.        ,  0.        ],\n",
       "        [ 0.        ,  0.        ,  0.        , ...,  0.        ,\n",
       "          0.        ,  0.        ]])"
      ]
     },
     "execution_count": 149,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 只要某个内存映像超出了作用域， 它就会被垃圾回收器回收， \n",
    "# 之前对其所做的任何修改都会被写入磁盘。 \n",
    "\n",
    "# 当打开一个已经存在的内存映像时， 仍然需要指明数据类型和形状， 因为磁盘上的那个文件只是一块二进制数据而已，没有任何元数据：\n",
    "mmap = np.memmap('mymmap', dtype='float64', shape=(10000, 10000))\n",
    "\n",
    "mmap"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 150,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 内存映像可以使用前面介绍的结构化或嵌套 dtype"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 151,
   "metadata": {},
   "outputs": [],
   "source": [
    "# HDF5 及其他数组存储方式\n",
    "\n",
    "# PyTables 和 h5py 这两个 Python 项目可以将 NumPy 的数组数据存储为高效且可压缩的 HDF5 格式\n",
    "# HDF 意思是 “层次化数据格式” , 可以安全地将好几百 GB 甚至 TB 的数据存储为 HDF5格式\n",
    "\n",
    "# 要学习 Python 使用 HDF5， 请参考 pandas 线上文档"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 152,
   "metadata": {},
   "outputs": [],
   "source": [
    "# A.9 性能建议\n",
    "\n",
    "# 使用 NumPy 的代码的性能一般都很不错， 因为数组运算一般都比纯 Python 循环快得多\n",
    "# 下面大致列出了一些需要注意的事项\n",
    "#     1、将Python循环和条件逻辑转换为数组运算和布尔数组运算。\n",
    "#     2、尽量使用广播。\n",
    "#     3、避免复制数据， 尽量使用数组视图（即切片） 。\n",
    "#     4、利用 ufunc 及其各种方法。\n",
    "\n",
    "\n",
    "# 如果单用 NumPy 无论如何都达不到所需的性能指标， 就可以考虑一下用 C、 Fortran 或 Cython 来编写代码\n",
    "\n",
    "# 在工作中经常会用到 Cython（http://cython.org），因为它不用花费我太多精力就能得到 C语言 那样的性能"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 153,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "  C_CONTIGUOUS : True\n",
       "  F_CONTIGUOUS : False\n",
       "  OWNDATA : True\n",
       "  WRITEABLE : True\n",
       "  ALIGNED : True\n",
       "  WRITEBACKIFCOPY : False\n",
       "  UPDATEIFCOPY : False"
      ]
     },
     "execution_count": 153,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 连续内存的重要性\n",
    "\n",
    "# 虽然这个话题有点超出范围， 但还是要提一下， 因为在某些应用场景中， 数组的内存布局可以对计算速度造成极大的影响\n",
    "#  这是因为性能差别在一定程度上跟 CPU 的高速缓存（cache） 体系有关\n",
    "\n",
    "#  运算过程中访问连续内存块（例如， 对以 C 顺序存储的数组的行求和） 一般是最快的，\n",
    "#  因为内存子系统会将适当的内存块缓存到超高速的 L1 或 L2 CPU Cache中\n",
    "\n",
    "# 此外， NumPy 的 C语言基础代码（某些） 对连续存储的情况进行了优化处理， 这样就能避免一些跨越式的内存访问\n",
    "\n",
    "\n",
    "# 一个数组的内存布局是连续的， 就是说元素是以它们在数组中出现的顺序（即 Fortran 型（列优先） 或 C型（行优先））存储在内存中的\n",
    "# 默认情况下， NumPy 数组是以 C型连续的方式创建的\n",
    "\n",
    "# 列优先的数组（比如 C型连续数组的转置） 也被称为 Fortran型连续\n",
    "#  通过 ndarray 的 flags 属性即可查看这些信息\n",
    "\n",
    "arr_c = np.ones((1000, 1000), order='C')\n",
    "\n",
    "arr_f = np.ones((1000, 1000), order='F')\n",
    "\n",
    "arr_c.flags"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 154,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "  C_CONTIGUOUS : False\n",
       "  F_CONTIGUOUS : True\n",
       "  OWNDATA : True\n",
       "  WRITEABLE : True\n",
       "  ALIGNED : True\n",
       "  WRITEBACKIFCOPY : False\n",
       "  UPDATEIFCOPY : False"
      ]
     },
     "execution_count": 154,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr_f.flags"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 155,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 155,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr_f.flags.f_contiguous"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 156,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3.18 ms ± 167 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
     ]
    }
   ],
   "source": [
    "# 在这个例子中， 对两个数组的行进行求和计算， \n",
    "# 理论上说， arr_c 会比 arr_f快， 因为 arr_c 的行在内存中是连续的\n",
    "\n",
    "# 可以在 IPython 中用 %timeit 来确认一下\n",
    "%timeit arr_c.sum(1)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 157,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2.56 ms ± 436 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n"
     ]
    }
   ],
   "source": [
    "%timeit arr_f.sum(1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 158,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "  C_CONTIGUOUS : True\n",
       "  F_CONTIGUOUS : False\n",
       "  OWNDATA : True\n",
       "  WRITEABLE : True\n",
       "  ALIGNED : True\n",
       "  WRITEBACKIFCOPY : False\n",
       "  UPDATEIFCOPY : False"
      ]
     },
     "execution_count": 158,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 如果想从 NumPy 中提升性能， 这里就应该是下手的地方\n",
    "\n",
    "# 如果数组的内存顺序不符合要求，使用 copy 并传入'C'或'F'即可解决该问题：\n",
    "arr_f.copy('C').flags"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 159,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 159,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 注意， 在构造数组的视图时， 其结果不一定是连续的：\n",
    "arr_c[:50].flags.contiguous"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 160,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "  C_CONTIGUOUS : False\n",
       "  F_CONTIGUOUS : False\n",
       "  OWNDATA : False\n",
       "  WRITEABLE : True\n",
       "  ALIGNED : True\n",
       "  WRITEBACKIFCOPY : False\n",
       "  UPDATEIFCOPY : False"
      ]
     },
     "execution_count": 160,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr_c[:, :50].flags"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
